<?php
namespace App\Http\Controllers\V2\Shop;

use App\Http\Controllers\Controller;
use App\Jobs\VerifyCouponJob;
use App\Libraries\Decorator\Image\ImagesDecorator;
use App\Libraries\Decorator\Image\NoImagesDecorator;
use App\Libraries\Decorator\Tool\IsEndDecorator;
use App\Libraries\Tools\ConstVar;
use App\Libraries\Tools\Tools;
use App\Models\Shop\Shop;
use App\Models\Shop\ShopComment;
use App\Models\Shop\ShopContent;
use App\Models\Shop\ShopCoupon;
use App\Models\Shop\ShopCouponPurchase;
use App\Models\Shop\ShopFav;
use App\Models\Shop\ShopManager;
use App\Models\Shop\ShopService;
use App\Models\Shop\ShopStatistic;
use App\Models\Tool\BadWord;
use App\Models\User\User;
use Dingo\Api\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use App\Libraries\Decorator\Image\CoverDecorator;
use OSS\OssClient;
use OSS\Core\OssException;


class ShopController extends Controller{


    protected $shop;
    protected $shop_detail;
    protected $shop_comment;
    protected $cover_decorator;
    protected $images_decorator;
    protected $comment_decorator;
    protected $is_end_decorator;
    protected $no_images_decorator;

    public function __construct(Shop $shop, CoverDecorator $cover_decorator,
                                ImagesDecorator $images_decorator,
                                NoImagesDecorator $no_images_decorator,
                                IsEndDecorator $is_end_decorator){
        $this->shop = $shop;
        $this->cover_decorator = $cover_decorator;
        $this->images_decorator = $images_decorator;
        $this->no_images_decorator = $no_images_decorator;
        $this->is_end_decorator = $is_end_decorator;
    }

    /**
     * 商家列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function shops(Request $request){
        $validator = Validator::make(
            $request->all(), [
            'user_lng' => 'required|numeric',
            'user_lat' => 'required|numeric',
            'lng' => 'required_without_all:keyword,city_id,district_id,fav,type|numeric',
            'lat' => 'required_without_all:keyword,city_id,district_id,fav,type|numeric',
            'lng_radius' => 'required_without_all:keyword,city_id,district_id,fav,type|numeric',
            'lat_radius' => 'required_without_all:keyword,city_id,district_id,fav,type|numeric',
            'city_id' => 'numeric',
            'district_id' => 'integer',
            'user_city_id' => 'numeric',
            'type' => 'in:0,1,2,3,4,5,12',
            'order' => 'required|in:1,2,3,4,5',//1-距离 2-评价 3-价格 4-智能 5-人气
            'keyword' => 'string',
            'distance' => 'numeric',
            'fav' => 'in:0,1',
            'page' => 'required|integer',
            'size' => 'required|integer',
        ], [
            'user_lng.required' => '10001',
            'user_lng.numeric' => '10002',
            'user_lat.required' => '10001',
            'user_lat.numeric' => '10002',
            'lng.required_without_all' => '10001',
            'lng.numeric' => '10002',
            'lat.required_without_all' => '10001',
            'lat.numeric' => '10002',
            'lng_radius.required_without_all' => '10001',
            'lng_radius.numeric' => '10002',
            'lat_radius.required_without_all' => '10001',
            'lat_radius.numeric' => '10002',
            'user_city_id.required' => '10001',
            'user_city_id.numeric' => '10002',
            'city_id.numeric' => '10002',
            'district_id.integer' => '10002',
            'type.in' => '10002',
            'order.required' => '10001',
            'order.in' => '10002',
            'keyword.string' => '10002',
            'distance.numeric' => '10002',
            'fav.in' => '10002',
            'page.required' => '10001',
            'page.integer' => '10002',
            'size.required' => '10001',
            'size.integer' => '10002',
        ]);
        if ($validator->fails()) {
            return $this->sendFailResponse(400, $validator->errors()->first());
        }
        $this->shop->addDecorator($this->cover_decorator);
        $this->shop->addDecorator($this->no_images_decorator);
        $this->shop->addDecorator($this->is_end_decorator);
        $data = $this->shop->shopsV2($request, Auth::id());
        return $this->sendSuccessResponse($data);
    }


    /**
     * 商家申请进驻
     * @param Request $request
     * @param ShopContent $content
     * @param ShopService $service
     * @param ShopStatistic $statistic
     * @param ShopManager $manager
     * @return \Illuminate\Http\JsonResponse
     */
    public function applyShop(Request $request,
                              ShopContent $content,
                              ShopService $service,
                              ShopStatistic $statistic, ShopManager $manager){
        $validator = Validator::make(
            $request->all(), [
            'type' => 'required|in:1,2,3,4,5,6,7,9,11,12',
            'title' => 'required|string|max:50',
            'consumption' => 'required|integer',
            'cover' => 'required|image',
            'images.*' => 'image',
            'content' => 'string',
            'phone' => 'required|string|max:50',
            'province_id' => 'required|integer',
            'city_id' => 'required|integer',
            'district_id' => 'required|integer',
            'address' => 'required|string|max:200',
            'longitude' => 'required|numeric',
            'latitude' => 'required|numeric',
            'manager_name' => 'required|string|max:100',
        ], [
            'type.required' => '10001',
            'type.in' => '10002',
            'title.required' => '10001',
            'title.string' => '10002',
            'title.size' => '10002',
            'consumption.required' => '10001',
            'consumption.integer' => '10002',
            'cover.required' => '10001',
            'cover.image' => '10003',
            'images.*.image' => '10003',
            'content.string' => '10002',
            'phone.required' => '10001',
            'phone.string' => '10002',
            'phone.max' => '10002',
            'province_id.required' => '10001',
            'province_id.integer' => '10002',
            'city_id.required' => '10001',
            'city_id.integer' => '10002',
            'district_id.required' => '10001',
            'district_id.integer' => '10002',
            'address.required' => '10001',
            'address.string' => '10002',
            'address.size' => '10002',
            'longitude.required' => '10001',
            'longitude.numeric' => '10002',
            'latitude.required' => '10001',
            'latitude.numeric' => '10002',
            'manager_name.required' => '10001',
            'manager_name.string' => '10002',
            'manager_name.size' => '10002',
        ]);
        if ($validator->fails()) {
            return $this->sendFailResponse(400, $validator->errors()->first());
        }
        if(!empty($request['title'])){
            $request['title'] = Tools::removeXSS($request['title']);
        }
        if(!empty($request['consumption'])){
            $request['consumption'] = Tools::removeXSS($request['consumption']);
        }
        if(!empty($request['phone'])){
            $request['phone'] = Tools::removeXSS($request['phone']);
        }
        if(!empty($request['address'])){
            $request['address'] = Tools::removeXSS($request['address']);
        }
        if(!empty($request['content'])){
            $request['content'] = Tools::removeXSS($request['content']);
        }
        if(!empty($request['manager_name'])){
            $request['manager_name'] = Tools::removeXSS($request['manager_name']);
        }

        DB::beginTransaction();
        try{
            $ossClient = new OssClient(env('ALIYUN_ID'), env('ALIYUN_KEY'), env('ALIYUN_ENDPOINT'));
            $bucket = env('ALIYUN_BUCKET');
            $images = [];
            $this->shop->title = $request['title'];
            $this->shop->status = 0;
            $this->shop->verify_status = 0;
            $this->shop->type = $request['type'];
            $this->shop->consumption = $request['consumption'];
            if($request->hasFile('cover') && $request->file('cover')->isValid()){
                $object = 'image/'.uniqid().'.'.$request->file('cover')->extension();
                $ossClient->uploadFile($bucket, $object, $request->file('cover')->getFileInfo());
                $this->shop->cover = $object;
            }
            if(!empty($request['images'])){
                foreach($request->file('images') as $v){
                    if($v->isValid()){
                        $object = 'image/'.uniqid().'.'.$v->extension();
                        $ossClient->uploadFile($bucket, $object, $v->getFileInfo());
                        $images[] = $object;
                    }
                }
            }
            if(!empty($images)){
                $this->shop->images = json_encode($images);
            }
            $this->shop->phone = $request['phone'];
            $this->shop->province_id = $request['province_id'];
            $this->shop->city_id = $request['city_id'];
            $this->shop->district_id = $request['district_id'];
            $this->shop->address = $request['address'];
            $this->shop->longitude = $request['longitude'];
            $this->shop->latitude = $request['latitude'];
            $this->shop->save();

            $manager->user_id = Auth::id();
            $manager->shop_id = $this->shop->shop_id;
            $manager->name = $request['manager_name'];
            $manager->status = 0;
            $manager->level = 1;
            $manager->company = $request['title'];
            $manager->company_phone = $request['phone'];
            $manager->save();

            $content->shop_id = $this->shop->shop_id;
            $content->content = empty($request['content'])?'':$request['content'];
            $content->save();

//            if(!empty($request['services'])){
//                $services = json_decode($request['services'], true);
//                foreach($services as $v){
//                    $service->shop_id = $this->shop->shop_id;
//                    $service->name = $v['name'];
//                    $service->price = $v['price'];
//                    $service->save();
//                    $service = new ShopService();
//                }
//            }
            $statistic->shop_id = $this->shop->shop_id;
            $statistic->save();
            DB::commit();
            return $this->sendSuccessResponse(['shop_id'=>$this->shop->shop_id]);
        }catch(OssException $e){
            DB::rollBack();
            return $this->sendFailResponse(400,40003);
        }catch(\Exception $e){
            DB::rollBack();
            return $this->sendFailResponse(500,50000);
        }
    }


    /**
     * 检查是否经理
     * @param $shop_id
     * @return bool
     */
    private function checkIfManager($shop_id){
        $shopManager = new ShopManager();
        $shopManager = $shopManager->where('user_id', Auth::id())
            ->where('shop_id', $shop_id)
            ->where('status', 1)
            ->first();
        if(empty($shopManager)){
            return false;
        }
        return true;
    }

    /**
     * @param $user_id
     * @param ShopManager $shopManager
     * @return ShopManager|null
     */
    private function checkIfOwner($user_id, ShopManager $shopManager){
        $shopManager = $shopManager->where('user_id', $user_id)
            ->where('status', 1)
            ->where('level', 1)
            ->first();
        if(empty($shopManager)){
            return null;
        }
        return $shopManager;
    }

    /**
     * 套餐订单详情
     * @param $code
     * @param ShopCouponPurchase $shopCouponPurchase
     * @return \Illuminate\Http\JsonResponse
     */
    public function couponPurchase($code, ShopCouponPurchase $shopCouponPurchase){
        $valid_data['code'] = $code;
        $validator = Validator::make($valid_data, [
            'code' => 'required|integer',
        ], [
            'code.required' => '10001',
            'code.integer' => '10002',
        ]);
        if ($validator->fails()) {
            return $this->sendFailResponse(400, $validator->errors()->first());
        }

        $shopCouponPurchase->addDecorator($this->cover_decorator);
        $shopCouponPurchase->addDecorator($this->images_decorator);
        $data = $shopCouponPurchase->getPurchaseByCodeV2($code);
        return $this->sendSuccessResponse($data);
    }

    /**
     * 套餐订单列表
     * @param Request $request
     * @param ShopCouponPurchase $shopCouponPurchase
     * @param ShopManager $shopManager
     * @return \Illuminate\Http\JsonResponse
     */
    public function couponPurchases(Request $request, ShopCouponPurchase $shopCouponPurchase,
                                    ShopManager $shopManager){
        $valid_data = $request->all();
        if(!empty($request['status'])){
            $valid_data['status'] = \GuzzleHttp\json_decode($request['status'], true);
        }
        $validator = Validator::make($valid_data, [
            'page' => 'required|integer',
            'size' => 'required|integer',
            'status.*' => 'in:0,1,2,3,4,5',
            'status' => 'array',
            'shop_id' => 'integer',
            'start_at' => 'integer',
            'end_at' => 'integer',
        ], [
            'page.required' => '10001',
            'page.integer' => '10002',
            'size.required' => '10001',
            'size.integer' => '10002',
            'status.*.in' => '10002',
            'status.array' => '10002',
            'shop_id.integer' => '10002',
            'start_at.integer' => '10002',
            'end_at.integer' => '10002',
        ]);
        if ($validator->fails()) {
            return $this->sendFailResponse(400, $validator->errors()->first());
        }
        if(!empty($request['shop_id'])){
            $manager = $shopManager::where('shop_id', $request['shop_id'])
                ->where('user_id', Auth::id())
                ->where('status', 1)
                ->first();
            if(empty($manager)){
                return $this->sendFailResponse(400, 40101);
            }
        }
        $shopCouponPurchase->addDecorator($this->cover_decorator);
        $shopCouponPurchase->addDecorator($this->images_decorator);
        $shopCouponPurchase->addDecorator($this->is_end_decorator);

        $data = $shopCouponPurchase->getPurchasesV2(
            $request['page'],
            $request['size'],
            $request['start_at']??null,
            $request['end_at']??null,
            $valid_data['status']??null,
            $request['shop_id']??null
        );
        return $this->sendSuccessResponse($data);
    }
}